var listColumns = [[
    {field: "id", checkbox: true},
    {field: "workOrderId", title: "工单号", align: "center", width: 100},
    {field: "createMobile", title: "来电号码", align: "center", width: 100,hidden:true},
    {field: "creatorName", title: "报修人", align: "center", width: 100},
    {field: "callerDeptName", title: "部门", align: "center", width: 120},
    {field: "address", title: "地点", align: "center", width: 120},
    {field: "source", title: "工单来源", align: "center", width: 120},
    {field: "floor", title: "楼层", align: "center", width: 120  ,hidden:true},
    {field: "expectTime", title: "维修时间", align: "center", width: 120},
    {field: "machineType", title: "选项", align: "center", width: 100},
    {field: "repaireSubject", title: "判定常用", align: "center", width: 150},
    {field: "status", title: "当前状态", align: "center", width: 80,formatter:function (value) {
        switch(value){
            // 00:座席处理 01:调配 02:已接单 03:服务中 04:结束服务
            case "00": return "待流转";
            case "01": return "待调配";
            case "02": return "已接单";
            case "03": return "服务中";
            case "04": return "服务完成待评价";
            case "05": return "已评价";
            case "06": return "待接单";
            case "08": return "异常结束";
            default: return "";
        }
    }},
    {field: "currentName", title: "负责工程师", align: "center", width: 150},
    {field: "createTime", title: "创建时间", align: "center", width: 100,formatter:function (value) {
        return formatDate(value);
    }},
    {field: "beginProcessTime", title: "开始时间", align: "center", width: 100,hidden:true,formatter:function (value) {
        return formatDate(value);
    }},
    {field: "endProcessTime", title: "结束时间", align: "center", width: 100,hidden:true,formatter:function (value) {
        return formatDate(value);
    }},
    {field: "description", title: "备注", align: "center", width: 150},
    {field: "picAddress", title: "图片", align: "center",formatter:function (value, rowData,index) {
            // if(value == null || value == ''){
            //     return "";
            // }
            return '<a class="layui-btn layui-btn-xs" onclick="previewImg(\''+rowData.id+'\')" style="text-decoration: none">查看</a>';
    }},
    {
        field: "handle", title: "处理", align: "center", width: 150, formatter: function (value, rowData,index) {
        var flag = rowData.status;
        var roleId = $("#session_roleId").val();
        if(roleId != 2 && roleId != 4){
            return "";
        }
       /* if (flag=='00' ) {
            return '<a class="layui-btn layui-btn-xs" onclick="handleCirculation('+rowData.id+','+index+')" style="text-decoration: none">流转</a>'
            + '<a class="layui-btn layui-btn-xs" onclick="handleRecord('+rowData.id+','+flag+')" style="text-decoration: none">派单</a>';
        }*/
            if (flag=='01' || flag=='02' || flag=='03' || flag == '06') {
                return '<span class="button-dropdown button-rounded button-dropdown-primary" data-buttons="dropdown">' +
                    '<button  class="button button-primary button-rounded button-raised button-longshadow-right button-tiny" style="margin: 5px;" >' +
                    '<i class="fa fa-bars"></i>&nbsp;<span>操作</span>&nbsp;<i class="fa fa-caret-down"></i>' +
                    '</button>' +
                    '<ul class="button-dropdown-list is-below">' +
                    '<li><a  href="javascript:;" onclick="handleRecord('+rowData.id+','+flag+')">&nbsp;派单</a></li>' +
                    '<li><a  href="javascript:;" onclick="editData('+rowData.id+','+index+')">&nbsp;编辑</a></li>' +
                    '<li class="button-dropdown-divider">' +
                    '<a  href="javascript:;" onclick="addPic('+rowData.id+','+index+')">&nbsp;上传</a>' +
                    '</li>' +
                    '<li><a  href="javascript:;" onclick="endServer('+rowData.id+','+index+')">&nbsp;完成</a></li>' +
                    '<li><a  href="javascript:;" onclick="exceptionEnd('+rowData.id+','+index+')">&nbsp;异常完成</a></li>' +
                    '<li><a  href="javascript:;" onclick="viewCycle('+rowData.id+','+index+')">&nbsp;查看流转信息</a></li>' +
                    '</ul>' +
                    '</span>';
                /*return '<div class="btn-group" role="group" aria-label="操作">'+
                '<button type="button"  onclick="handleRecord('+rowData.id+','+flag+')" style="text-decoration: none">派单</button>'
                    +'<button type="button"  onclick="editData('+rowData.id+','+index+')" style="text-decoration: none">编辑</button>' +
                    '<button type="button"  onclick="addPic('+rowData.id+','+index+')" style="text-decoration: none">上传</button>'+
                    '<button type="button"  onclick="endServer('+rowData.id+','+index+')" style="text-decoration: none">完成</button>'+
                    '<button type="button" onclick="exceptionEnd('+rowData.id+','+index+')" style="text-decoration: none">异常完成</button>'+
                    '</div>';*/
            }else {
                return '<a class="layui-btn layui-btn-xs" onclick="viewCycle('+rowData.id+','+index+')" style="text-decoration: none">查看流转信息</a>'
            }
    }
    }
]];
function formatDate(value) {
    if(value == null || value == ''){
        return "";
    }
    return value.substr(5,value.length);
}

function reviewPic(value){
    if(value == null || value == ''){
        return "";
    }
    return '<a class="layui-btn layui-btn-xs" onclick="previewImg(\''+value+'\')" style="text-decoration: none">查看</a>';
}

layui.config({
    base: "../static/agent-ui/js/"
});

$.fn.toJSON = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        var name = this.name;
        var value = this.value;
        var paths = this.name.split(".");
        var len = paths.length;
        var obj = o;
        $.each(paths, function (i, e) {
            if (i == len - 1) {
                if (obj[e]) {
                    if (!obj[e].push) {
                        obj[e] = [obj[e]];
                    }
                    obj[e].push(value || '');
                } else {
                    obj[e] = value || '';
                }
            } else {
                if (!obj[e]) {
                    obj[e] = {};
                }
            }
            obj = o[e];
        });
    });
    return o;
};
String.prototype.endWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
        return false;
    if(this.substring(this.length-str.length)==str)
        return true;
    else
        return false;
    return true;
}

String.prototype.startWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
        return false;
    if(this.substr(0,str.length)==str)
        return true;
    else
        return false;
    return true;
}
layui.use(["laypage", "layer", "validator", "tools", "form", "select", "laydate","autocomplete","upload","carousel"], function () {
    var form = layui.form;
    var date = layui.laydate;

    var autocomplete = layui.autocomplete;
    date.render({
        elem: '#ringTime',
        // type: 'datetime',
        range: true
    });


    var layer=layui.layer;

    $(function () {
        $('#list').datagrid({
            columns: listColumns,
            fitColumns: false,
            fit: true,
            singleSelect: true,
            pagination: true,
            pageSize: 30,
            pageList: [30, 50, 100, 1000],
            toolbar: '#receivedListHeader',
            method: 'get',
            url: ctx +'/repaireInfo/list',
            onLoadSuccess:function(data) {
                for(var i=0;i<data.rows.length;i++){
                    var value=data.rows[i].status;
                    switch(value){
                        // 01:调配 02:已接单 03:服务中 04:结束服务
                        case "01":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-01");
                            break;
                        case "02":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-02");
                            break;
                        case "03":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-03");
                            break;
                        case "04":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-04");
                            break;
                        case "05":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-05");
                            break;
                        case "06":
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-06");
                            break;
                        default:
                            $(".datagrid-view2").find(".datagrid-body").find(".datagrid-row").eq(i).addClass("datagrid-row-00");
                    }
                }
            }
        });
    });

    $('#search_submit').on('click', function () {
        $('#list').datagrid('load', $('#search_form').toJSON());
    });

    $("#exportData").on("click",function () {
        $('#search_form').attr("action",ctx + '/repaireInfo/export');
        $('#search_form').submit();
    });
    $("#addData").on("click", function(){
        /* 再弹出添加界面 */
        layer.open({
            type:1,
            title:"添加工单",
            skin:"myclass",
            area:["50%"],
            content:$("#add").html(),
            success:function (layero,index) {
                addAutoComplete(layero);
                layero.addClass('layui-form');
                layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
                $(layero).find('select[name=machineType]').html(valMachineType());
                form.on('select(machineTypeFilter)', function(data){
                    changeSubject(layero);
                    form.render();
                });
                form.on('select(addressFilter)', function(data){
                    selectfloor(layero)
                    form.render();
                });
                form.render();
            },
            btn:['提交'],
            yes:function (index,layero) {
                form.on('submit(fromContent)', function (data) {
                    add(index,'1',layero)
                });
            }
        });
    });



// 添加自动填充
function addAutoComplete(layero) {
    autocomplete.render({
        elem: $(layero).find('input[name=email]')[0],
        url: ctx+'/user/findByEmail',
        template_val: '{{d.email}}',
        template_txt: '{{d.email}} <span class=\'layui-badge layui-bg-gray\'>{{d.displayName}}</span>',
        onselect: function (resp) {
            console.info(resp)
        }
    })

}
});


// 给服务时间赋值
function valExpectTime(expectTime) {
    var htmlStr = "<option value=''>请选择...</option>";
    if(expectTime =='上午' || expectTime == '下午'){
        htmlStr+="<option value='上午'>上午</option><option value='下午'>下午</option>";
    }else{
        for(var i=9;i<=17;i+=0.5){
            var time;
            if((i+'').endWith('.5')){
                time  = (i-0.5)+':30  -  '+(i+0.5)+':00';
            }else{
                time = i+':00  -  '+i+':30';
            }
            htmlStr +="<option value='"+time+"'>"+time+"</option>";
        }
    }
    return htmlStr;
}
// 给分类赋值
function valMachineType() {
    var htmlStr = "<option value=''>请选择...</option>";
    $.each(repaireSubject,function (name,value) {
        htmlStr += "<option value = '"+value.value+"'>"+value.text+"</option>";
    });
    return htmlStr;
}
var addBtn = true;
function add(index,status,layero) {
    if(!addBtn){
        return;
    }
    addBtn = false;
    var email = $(layero).find('input[name=email]').val();
    //var source = $(layero).find('select[name=source]').val();
    var machineType = $(layero).find('select[name=machineType]').val();
    var repaireSubjectVal = $(layero).find('select[name=repaireSubject]').val();
    var address = $(layero).find('select[name=address]').val();
    var floor = $(layero).find('select[name=floor]').val();
    var description = $(layero).find('input[name=description]').val();
    $.ajax({
        url:ctx+'/repaireInfo/add',
        type : 'POST',
        data:
            {email:email,
            machineType:machineType,
            source:'5',// 网页新增类型为 其他 5
            repaireSubject:repaireSubjectVal,
            address:address,
            floor:floor,
            description:description
        },
        success:function (result) {
            addBtn = true;
            var layer = layui.layer;
            var json = JSON.parse(result);
            if(json.code=='0'){
                layer.close(index);
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }

        },
        error:function (result) {
            addBtn = true;
            var json = JSON.parse(result);
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: json.msg
            });

        }
    });
}

function changeReason(val) {
    var endReason = $(this).val();
    if(endReason == '3' || endReason == '4'){
        $("#engineerDiv").removeAttr("style");
    }
}
// 查看流转信息
function viewCycle(id) {
    getCycleInfo(id,function (data) {
        layer.open({
            type: 1,
            title: "流转信息",
            skin: "myclass",
            area: ["50%", "70%"],
            content: $("#repaireCycleDiv").html(),
            success: function (layero, index) {
                var form = layui.form; //只有执行了这一步，部分表单元素才会自动修饰成功
                if(data.length >0){
                    var json = data[0]
                    $(layero).find('input[name=creatorName]').val(json.creatorName);
                    $(layero).find('input[name=callerDeptName]').val(json.callerDeptName);
                    $(layero).find('input[name=address]').val(json.address);
                    $(layero).find('input[name=machineType]').val(json.machineType);
                    $(layero).find('input[name=repaireSubject]').val(json.repaireSubject);
                    $(layero).find('input[name=description]').val(json.description);
                    $(layero).find('input[name=createTime]').val(json.createTime);
                    $(layero).find('input[name=assignTime]').val(json.assignTime);
                    $(layero).find('input[name=acceptTime]').val(json.acceptTime);
                    if(json.currentName != null && json.currentName !=''){
                        $(layero).find('span[name=currentName]').text(json.currentName);
                    }
                    var allocationVOList = json.allocationVOList
                    if(allocationVOList !=null && allocationVOList.length>0){
                        var html = "";
                        $.each(allocationVOList,function (i,v) {
                            html += "<div class=\"layui-form-item\">" +
                                "                <label class=\"layui-form-label\">转单时间</label>" +
                                "                <div class=\"layui-input-inline\">" +
                                "                    <input name=\"allocationTime\" class=\"layui-input\"  value='"+v.allocationTime+"' disabled/>" +
                                "                </div>" +
                                "            </div>"+
                            "<div class=\"layui-form-item\">" +
                                "                <label class=\"layui-form-label\">转单工程师</label>" +
                                "                <div class=\"layui-input-inline\">" +
                                "                    <input name=\"remark\" class=\"layui-input\"  value='"+v.creatorName+"' disabled/>" +
                                "                </div>" +
                                "            </div>";
                        });
                        $(layero).find('#repaireCycle_form').append(html);
                    }
                    form.render()
                }

            }
        })
    })
}

function getCycleInfo(id,callback) {
    $.ajax({
        url: ctx + "/repaireInfo/searchCycle/"+id,
        method: 'get',
        dataType: 'json',
        async: false,
        success: function (result) {
            if(result.code == '0' ){
                if(callback){
                    callback(result.data);
                }
            }
        },
        error: function (result) {

        }
    })
}
// 异常完成
function exceptionEnd(id) {
    var form = layui.form;
    layer.open({
        type: 1,
        title: "异常关单",
        skin: "myclass",
        area: ["50%", "70%"],
        content: $("#exceptionEnd").html(),
        success: function (layero, index) {
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            form.on('select(endReasonFilter)', function(data){
                var _endReason = $(layero).find('select[name=endReason]').val();
                if(_endReason=='03' || _endReason=='04') {
                    $(layero).find('div[id=engineerDiv]').removeAttr("style");
                    getEngineer(layero,'/repaireInfo/engineer');
                    form.render();
                }else{
                    $(layero).find('div[id=engineerDiv]').attr("style","display: none;");
                    form.render();
                }
            });
            form.render();
        },
        btn: ['提交','关闭'],
        yes:function (index,layero) {
            var jsonData = $(layero).find("form").toJSON();
            insertExceptionEnd(id,jsonData,function () {
                layer.close(index);
            });
        },
        btn2:function (index,layero) {
            layer.close(index);
        }
    })
}
var exceptionEndBtn = true;
function insertExceptionEnd(id,jsonData,callback) {
    if(!exceptionEndBtn){
        return;
    }
    exceptionEndBtn = false;
    $.ajax({
        url:ctx+'/repaireInfo/exceptionEnd/'+id+"?userName="+jsonData.currentId+"&exceptionReason="+jsonData.endReason,
        type : 'GET',
        success:function (result) {
            var json = JSON.parse(result);
            exceptionEndBtn = true;
            if(json.code=='0'){
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }
            if(callback){
                callback();
            }
        }
    });
}
// 完成
function endServer(id) {
    var userName = $("#session_userName").val();
    $.ajax({
        url:ctx+'/repaireInfo/endServer/'+id+"/"+userName,
        type : 'POST',
        success:function (result) {
            var json = JSON.parse(result);
            if(json.code=='0'){
                $('#list').datagrid('reload');
            }else{
                layer.open({
                    title: '报错了'
                    ,content: json.msg
                });
            }
        }
    });
}
// 定义files用于存储选择的文件
var files;

// 坐席上传图片
function addPic(id) {
    layer.open({
        type: 1,
        title: "上传图片",
        skin: "myclass",
        area: ["50%", "70%"],
        content: $("#uploadPic").html(),
        success: function (layero, index) {
            renderUpload(layero);
        },
        btn: ['上传','关闭'],
        yes:function (index,layero) {
            uploadPic(id,function () {
                layer.close(index);
            });
        },
        btn2:function (index,layero) {
            files = [];
            layer.close(index);
        }
    })
}

function uploadPic(id,callback) {
    var formData = new FormData();
    // 通过append方法添加key为file值为图片的数据，由于我们是将选择的文件逐个添加的，所以后台接收到的文件和我们选择文件的顺序是一致的
    for (var i in files) {<!-- -->
        formData.append("files", files[i]);
    }
    formData.append("id",id);
    // ajax上传
    $.ajax({
        url: '/repairePic/insert',
        type: "post",
        dataType: "json",
        async: false,
        contentType: false,
        processData: false,
        data: formData,
        success: function (result) {
            if (result.code == '0') {
                layer.msg("上传成功！", {icon: 6});
                if(callback !=null){
                    callback();
                }
            } else {
                layer.msg(result.msg, {icon: 5});

            }
        }
});

}
function renderUpload(layero) {
    //多图片上传
        var upload = layui.upload;
        $('.addPictures').off('click')
        $('.addPictures').off('change')
        $('.addPictures').data('haveEvents', false);
        var uploadInst = upload.render({
            elem: '.addPictures'
            // ,url: 'https://httpbin.org/post' //改成您自己的上传接口
            ,multiple: true
            ,exts:'jpg|png|jpeg|gif'//设置可上传文件
            ,auto: false//选择文件后不自动上传
            ,accept: 'images', // 指定允许上传时校验的文件类型为图片类
            acceptMime: 'image/*', // 选择时只显示图片文件
            choose: function (obj) {
                // 将每次选择的文件追加到文件队列
                files = this.files = obj.pushFile();
                // 文件预览功能，由于获取的是本地的缓存文件，顺序可能会因为大小的问题乱序
                obj.preview(function (index, file, result) {
                    // 将选择的文件显示在文件预览区
                    var picDiv = '<div id="" class="file-iteme">' +
                        '<div class="handle"><i class="layui-icon layui-icon-delete"></i></div>' +
                        '<img style="width: 100px;height: 100px;" src='+ result +'>' +
                        '<div class="info">' + file.name + '</div>' +
                        '</div>';
                    $(layero).find('#pictures').append(picDiv);
                    // 添加右上角的删除操作
                    $(layero).find('.file-iteme .handle').on('click', function () {
                        delete files[index]; // 删除对应的图片
                        $(this).parent().remove();
                        uploadInst.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                });
            }
        });

}


function previewImg(id){
    getPicAddress(id,function (result) {
        if(result.length == 0){
            layer.open({
                title: '没有图片'
                ,content: "该工单没有上传图片"
            });
            return;
        }
            layer.open({
                type: 1,
                shade: false,
                title: false, //不显示标题
                //area:['600px','500px'],
                area: [780+'px', 450+'px'],
                content: $("#previewPic"),//捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                success: function (layero, index){

                    var imgHtml = "";
                    for(var i=0;i<result.length;i++){
                        imgHtml += "<div><img src='"+ctx + '/repaireInfo/preview?picAddress=' + encodeURI(encodeURI(result[i] ))+ "' style=\"width: 100%;height: 500px;\"/></div>";
                    }
                    $("#appendDiv").html(imgHtml);
                    var carousel = layui.carousel;
                    var ins = carousel.render({
                        elem: '#previewPic'
                        ,width: '778px'
                        ,height: '440px'
                        ,arrow: 'always' //始终显示箭头
                        //,anim: 'updown' //切换动画方式
                        ,autoplay: true
                        ,interval: 2000
                        , indicator: 'inside' //指示器位置，可选outside,none
                        ,anim: 'fade'
                    });
                },
                cancel: function () {
                    $("#appendDiv").empty();
                    //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
                }

            });


    });

}

function getPicAddress(id,callback) {
    $.ajax({
        url:ctx + "/repairePic/list?id="+id,
        method:'get',
        dataType:'json',
        async:false,
        success:function(result){
            if(result.code=='0'){
                data = result.data;
                if(callback != null){
                    callback(data);
                }
            }else{
                var layer = layui.layer;
                layer.open({
                    title: '报错了'
                    ,content: result.msg
                });
            }
        },
        error: function (result) {
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: result.msg
            });
        }
    });
}
// 编辑
function editData(id,index) {
    var rows = $('#list').datagrid('getRows');
    var json = rows[index];
    layer.open({
        type: 1,
        title: "编辑",
        skin: "myclass",
        area: ["500px", "500px"],
        content: $("#edit").html(),
        success: function (layero, index) {
            var form = layui.form;
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            $(layero).find('input[name=id]').val(json.id);
            $(layero).find('input[name=creatorName]').val(json.creatorName);
            $(layero).find('input[name=callerCompanyName]').val(json.callerCompanyName);
            $(layero).find('input[name=description]').val(json.description);
            $(layero).find('input[name=callerDeptName]').val(json.callerDeptName);
            $(layero).find('select[name=expectTime]').html(valExpectTime(json.expectTime));
            $(layero).find('select[name=expectTime]').val(json.expectTime);
            var _address = json.address.split("-")[0];
            $(layero).find('select[name=address] option').each(function (i,n) {
                if($(n).text()==_address) {
                    $(n).attr("selected", true);
                    selectfloor(layero);
                    $(layero).find('select[name=floor]').val(json.floor);
                }
            });
            form.on('select(addressFilter)', function(data){
                selectfloor(layero);
                form.render();
            });
            $(layero).find('select[name=machineType]').html(valMachineType());
            $(layero).find('select[name=machineType] option').each(function(i,n){
                if($(n).text()==json.machineType) {
                    $(n).attr("selected",true);
                    changeSubject(layero);
                    selectedRepaireSubject(layero,json.repaireSubject);
                }
            });
            form.on('select(machineTypeFilter)', function(data){
                changeSubject(layero);
                form.render();
            });
            form.render();
        },
        btn: ['提交'],
        yes:function (index,layero) {
            var form = layui.form;
            form.on('submit(fromContent)', function (data) {
                var jsonData = $(layero).find("form").toJSON();
                updateByCustomService(jsonData,function () {
                    layer.close(index);
                    $('#list').datagrid('reload');
                });
            });
        }
    })
}
// 选中判断常用
function selectedRepaireSubject(layero,repaireSubject) {
    $(layero).find('select[name=repaireSubject] option').each(function(i,n){
    if($(n).text()==repaireSubject) {
        $(n).attr("selected",true);
    }

    })
}
//  选择楼层
function selectfloor(layero) {
    var _address = $(layero).find('select[name=address]').val();
    var $floor = $(layero).find("select[name=floor]");
    $floor.empty();
    var floors= floor_json[_address];
    var floor_html = "";
    $.each(floors,function (i,v) {
        floor_html +="<option value='"+v+"'>"+v+"</option>";
    });
    $floor.html(floor_html);
}
//  更新操作
function handleRecord(id,flag){
        process_01(id,flag);
}
var repeatBtn = true;
// 售后接单的时候  弹出dialog  选择是否上门服务
// 如果不需要则直接填写相关说明，然后回单到话务员，如果需要，记录当前处理工单的开始时间
function process_01(id, flag) {
    layer.open({
        type:1,
        title:"调配",
        skin:"myclass",
        area:["500px","300px"],
        content:$("#process_01").html(),
        success:function (layero,index) {
            var form = layui.form;
            form.render();
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
            getEngineer(layero,'/repaireInfo/engineer');
        },
        btn:['提交'],
        yes:function (index,layero) {
            var form = layui.form;
            form.on('submit(fromContent)', function (data) {
                if (repeatBtn) {
                    var currentId = $(layero).find('select[name=currentId]').val();
                    if(currentId == null || currentId == '' ){
                        var layer = layui.layer;
                        layer.open({
                            title: '工程师为空'
                            ,content: '请选择工程师'
                        });
                        return;
                    }
                    repeatBtn = false;
                    var currentName = $(layero).find('select[name=currentId] option:selected').text();
                    var json = {"id": id, "currentId": currentId, "currentName": currentName}
                    update(json, function () {
                        layer.close(index);
                        $('#list').datagrid('reload');
                        repeatBtn = true;
                    });
                }
            });

        }
    });
}
function renderSelect(data,layero) {
    var optionString = "<option value=''>请选择...</option><option value='group'>IT维护组</option>";
    data.forEach((user,index) =>{
                optionString += "<option value = '"+user.userName+"'>"+user.displayName+"</option>";
            });
    $(layero).find('select[name=currentId]').append(optionString);
    var form = layui.form;
    form.render('select');
}
function getEngineer(layero,pash){
    $.ajax({
        url:ctx + pash,
        method:'get',
        dataType:'json',
        async:false,
        success:function(result){
            if(result.code=='0'){
                renderSelect(result.data,layero);
            }else{
                var layer = layui.layer;
                layer.open({
                    title: '报错了'
                    ,content: result.msg
                });
            }
        },
        error: function (result) {
            var layer = layui.layer;
            layer.open({
                title: '报错了'
                ,content: result.msg
            });
        }
    });
}

function process_2(id, flag) {
    layer.open({
        type:1,
        title:"处理事项",
        skin:"myclass",
        area:["500px","300px"],
        content:$("#huidan").html(),
        success:function (layero,index) {
            var form = layui.form;
            form.render();
            layero.addClass('layui-form');
            layero.find('.layui-layer-btn0').attr('lay-filter', 'fromContent').attr('lay-submit', '');//将按钮弄成能提交的
        },
        btn:['提交'],
        yes:function (index,layero) {
            var form = layui.form;
            form.on('submit(fromContent)', function (data) {
                var reason = $(layero).find('input[name=reason]').val();
                var processSpecification = $(layero).find('input[name=processSpecification]').val();
                var processRemark = $(layero).find('input[name=processRemark]').val();
                var json = {id:id,status:3,processSpecification:processSpecification,processRemark:processRemark,reason:reason};
                update(json,function () {
                    layer.close(index);
                    $('#list').datagrid('reload');
                });
            });
        }
    });
}
function update(json,callback) {
    $.ajax({
        url:ctx+'/repaireInfo/update',
        type : 'POST',
        data:json,
        success:function (result) {
            repeatBtn = true;
            var resultJson = JSON.parse(result);
            if(resultJson.code=='0'){
                if(callback !=null){
                    callback();
                }
            }else if(resultJson.code=='2'){ // 状态不对
                var layer = layui.layer;
                layer.confirm(resultJson.msg, {icon: 3, title:'提示'}, function(index){
                    //do something
                    json['enforce'] = true
                    enforceAllocation(json,callback);
                    layer.close(index);
                });
            }else { // 失败
                var layer = layui.layer;
                layer.open({
                    title: '派单失败'
                    ,content: resultJson.msg
                });
            }


        }
    });
}
// 强制派单
function enforceAllocation(json,callback) {
    $.ajax({
        url:ctx+'/repaireInfo/update',
        type : 'POST',
        data:json,
        success:function (result) {
            repeatBtn = true;
            var resultJson = JSON.parse(result);
            if(resultJson.code=='0'){
                if(callback !=null){
                    callback();
                }
            }else { // 失败
                var layer = layui.layer;
                layer.open({
                    title: '派单失败'
                    ,content: resultJson.msg
                });
            }


        }
    });
}

function updateByCustomService(json,callback) {
    $.ajax({
        url:ctx+'/repaireInfo/updateByCustomService',
        type : 'POST',
        data:json,
        success:function () {
            if(callback !=null){
                callback();
            }

        }
    });
}

